<template>
  <div style="margin-top:30px">
    <el-form ref="form" :rules="rules" :model="form" label-width="110px">
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="字段" prop="field" style="margin-right:15px">
              <el-input v-model="form.field" placeholder="请输入字段" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="字段展示名称" prop="fieldName" style="margin-right:15px">
              <el-input v-model="form.fieldName" placeholder="请输入字段展示名称" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="字段类型" prop="type" style="margin-right:15px">
              <el-select v-model="form.type" placeholder="请选择" clearable @change="changeDb">
                <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="数据来源" prop="source" style="margin-right:15px">
              <el-select v-model="form.source" placeholder="请选择" clearable>
                <el-option v-for="item in sourceOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="排序" prop="sort" style="margin-right:15px">
              <el-input v-model.number="form.sort" placeholder="请输入排序:越大越往后" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row v-if="form.source == 'diy'">
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="数据库字段" prop="dbField" style="margin-right:15px">
              <el-select v-model="form.dbField" placeholder="请选择" clearable>
                <el-option v-for="item in fieldList" :key="item.code" :label="getFieldLabel(item)" :value="item.code" />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="备注" prop="remark" style="margin-right:15px">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row v-if="form.source == 'cal'">
        <el-col :span="24">
          <el-form-item label="计算规则" prop="calObjList" style="margin-right:15px" :rules="{required: true, message: '请至少添加一条计算规则', trigger: 'blur'}">
            <template v-for="(calObj,index) in form.calObjList">
              <el-row :key="'cal'+index" style="margin-bottom:20px;">
                <el-col :span="8">
                  <el-form-item label-width="1px" :prop="'calObjList.'+index+'.firstField'" :rules="{required: true, message: '字段不能为空', trigger: 'blur'}">
                    <el-select v-model="calObj.firstField" placeholder="字段" clearable @change="handleChange('calObjList.'+index+'.firstField')">
                      <el-option v-for="item in calFieldList" :key="item.code" :label="getFieldLabel(item)" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="3">
                  <el-form-item label-width="1px" :prop="'calObjList.'+index+'.firstCalType'" :rules="{required: true, message: '算法不能为空', trigger: 'blur'}">
                    <el-select v-model="calObj.firstCalType" placeholder="算法" clearable @change="handleChange('calObjList.'+index+'.firstCalType')">
                      <el-option v-for="item in calOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="1px" :prop="'calObjList.'+index+'.secondFiled'" :rules="{required: true, message: '字段不能为空', trigger: 'blur'}">
                    <el-select v-model="calObj.secondFiled" placeholder="字段" clearable @change="handleChange('calObjList.'+index+'.secondFiled')">
                      <el-option v-for="item in calFieldList" :key="item.code" :label="getFieldLabel(item)" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="3">
                  <el-form-item label-width="1px" :prop="'calObjList.'+index+'.secondCalType'" :rules="{required: true, message: '算法不能为空', trigger: 'blur'}">
                    <el-select v-model="calObj.secondCalType" placeholder="算法" clearable @change="handleChange('calObjList.'+index+'.secondCalType')">
                      <el-option v-for="item in calOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="1" :offset="1" v-if="form.calObjList.length>1">
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="funcDelCalObj(index)" circle></el-button>
                </el-col>
              </el-row>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="6">
          <el-button type="success" icon="el-icon-circle-plus" @click="funcAddCalObj" round> 添加计算规则</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="funcCancel">取 消</el-button>
      <el-button type="primary" @click="funcSubmit">确 定</el-button>
    </div>
  </div>
</template>
<script>
    import request from '@/utils/request'
    import { getListDict } from '@/api/commonApi'
    export default {
        name: 'diyReportFieldEdit',
        data() {
            return {
                fieldList: [],
                allType:[],
                calFieldList: [],
                oneCalObj: {
                    firstField: '',
                    firstCalType: '',
                    secondFiled:'',
                    secondCalType: ''
                },
                emptyForm:{},
                form: {
                    code: '',
                    branchCode: '',
                    reportCode: '',
                    field: '',
                    fieldName: '',
                    type: 'str',
                    source: 'diy',
                    sort: '',
                    dbField: '',
                    calObjList: [
                        {
                            firstField: '',
                            firstCalType: '',
                            secondFiled:'',
                            secondCalType: ''
                        }
                    ],
                    calJson: '',
                    remark: '',
                },
                // 计算
                calOptions: [
                    { label: '加', value: 'add'},
                    { label: '减', value: 'subtract'},
                    { label: '乘', value: 'multiply'},
                    { label: '除', value: 'divide'}
                ],
                // 字段类型
                typeOptions: [
                    { label: '文本', value: 'str'},
                    { label: '数值', value: 'int'},
                    { label: '日期', value: 'date'}
                ],
                // 数据来源
                computedSourceOptions: [
                    { label: '自定义', value: 'diy'},
                    { label: '计算得出', value: 'cal'}
                ],
                //  // 数据来源
                otherSourceOptions: [
                    { label: '自定义', value: 'diy'},
                ],


                rules: {
                    reportCode: [
                        { required: true, message: '请输入自定义报表code', trigger: 'blur' },

                    ],
                    field: [
                        { required: true, message: '请输入字段', trigger: 'blur' },

                    ],
                    remark: [
                         { min: 1, max: 255, message: '长度在 1 到 255个字符', trigger: 'blur' }
                    ],
                    fieldName: [
                        { required: true, message: '请输入字段展示名称', trigger: 'blur' },

                    ],
                    type: [
                        { required: true, message: '请选择字段类型', trigger: 'blur' },
                    ],
                    source: [
                        { required: true, message: '请选择数据来源', trigger: 'blur' },
                    ],
                    sort: [
                        { required: false, type: 'number', message: '排序必须为数字值' }
                    ]
                }
            }
        },
        created() {
            this.form.reportCode = this.$route.query.code
            //保存空表单对象
            this.emptyForm =JSON.parse(JSON.stringify(this.form))
        },
        computed:{
              sourceOptions() {
               return  this.form.type == 'int' ? this.computedSourceOptions:this.otherSourceOptions
              }
        },
        methods: {
            // 清除
            handleChange(param){
              this.$refs['form'].clearValidate(param)
            },
            // 获取页面信息
            getInfo(code) {
                this.selectDict()
                //查询到数据之前先展示空表单
                this.form=JSON.parse(JSON.stringify(this.emptyForm))
                request({ url: `/wms/diyReportField/${code}`, method: 'get' }).then(response => {
                    this.form = response.data
                })
            },
             changeDb() {
                this.fieldList  = this.allType.filter(item =>item.remark == this.form.type )
                this.form.dbField = '';
            },
            //添加计算单元
            funcAddCalObj(){
                let obj =JSON.parse(JSON.stringify(this.oneCalObj))
                if(!this.form.calObjList){
                    this.form.calObjList = [
                        {
                            firstField: '',
                            firstCalType: '',
                            secondFiled:'',
                            secondCalType: ''
                        }
                    ]
                }
                this.form.calObjList.push(obj);
            },
            //删除计算单元(index 指定的下标)
            funcDelCalObj(index){
                this.form.calObjList.splice(index,1)
            },
            // 查询数据字典
            selectDict() {
                // 获取数据字典： 运单字段
                getListDict({ types: 'diyReportInventoryField,diyReportInventoryCalField' }).then(response => {
                    this.allType = response.data.filter(item => item.type === 'diyReportInventoryField')[0]['dictList']
                    this.fieldList  = this.allType.filter(item =>item.remark == this.form.type )
                    this.calFieldList = response.data.filter(item => item.type === 'diyReportInventoryCalField')[0]['dictList']
                })
            },

            //提交
            funcSubmit() {
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        const data = this.form
                        const rLoading = this.openLoading();
                        request({ url: '/wms/diyReportField', method: 'put', data: data }).then(response => {
                            rLoading.close();
                            this.$message({ message: response.msg, type: 'success' })
                            this.$emit('fatherEditMethod')
                        }).then(()=>this.$refs['form'].resetFields())
                    } else {
                        return false;
                    }
                });
            },
            //取消
            funcCancel() {
                this.$emit('fatherCancelMethod','edit')
            },
            //返回字段下拉选 名称
            getFieldLabel(item){
                return item.code + '(' + item.name + ')'
            }
        }
    }
</script>
<style lang="scss" scoped>
  .dialog-footer {
    margin:15px 0 15px 0;
    width: 175px;
    float: right;
  }
  .el-select {
    width: 100%;
  }
  .el-date-editor{
    width: 100%;
  }
</style>
